#include "devicemanager.h"
#include "ui_devicemanager.h"
#include <QFileDialog>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QMessageBox>
#include <QInputDialog>
#include <QCloseEvent>
#include <QDebug>
#include <QDateTime>

DeviceManager::DeviceManager(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::DeviceManager),
    deviceModel(nullptr),
    deviceManagementModel(nullptr),
    groupModel(nullptr),
    currentUserId(-1)
{
    ui->setupUi(this);
    this->setWindowTitle("设备管理系统");

    setupUI();
    setupConnections();

    // 记录系统启动日志
    LogManager::logSystem("设备管理模块", "设备管理模块初始化完成");
}

DeviceManager::~DeviceManager()
{
    delete ui;
    delete deviceModel;
    delete deviceManagementModel;
    delete groupModel;

    // 记录系统关闭日志
    LogManager::logSystem("设备管理模块", "设备管理模块销毁");
}

void DeviceManager::setCurrentUserId(int userId)
{
    this->currentUserId = userId;
}

void DeviceManager::setCurrentUserRole(const QString &role)
{
    this->currentUserRole = role;
            applyUserPermissions();  // 应用权限限制
}

void DeviceManager::setupUI()
{
    // 设置表格属性
    ui->tableViewDevices->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableViewDevices->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableViewDevices->setAlternatingRowColors(true);

    ui->tableViewDevices_2->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableViewDevices_2->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableViewDevices_2->setAlternatingRowColors(true);

    // 设置搜索框占位符
    ui->lineEditSearch->setPlaceholderText("输入设备名");

    // 设置分组查询下拉框
    ui->comboBoxGroupFilter->addItem("所有设备", "");

    // 默认显示设备管理标签页
    ui->tabWidget->setCurrentIndex(1);
}

void DeviceManager::setupConnections()
{
    // 连接工具栏动作
    connect(ui->actionOpenDB, &QAction::triggered, this, &DeviceManager::onOpenDatabase);
    connect(ui->actionAddDevice, &QAction::triggered, this, &DeviceManager::onAddDevice);
    connect(ui->actionDeleteDevice, &QAction::triggered, this, &DeviceManager::onDeleteDevice);
    connect(ui->actionSave, &QAction::triggered, this, &DeviceManager::onSaveChanges);
    connect(ui->actionAddGroup, &QAction::triggered, this, &DeviceManager::onAddGroup);
    connect(ui->actionDeleteGroup, &QAction::triggered, this, &DeviceManager::onDeleteGroup);

    // 连接按钮信号
    connect(ui->btnSearch, &QPushButton::clicked, this, &DeviceManager::onSearchDevice);

    // 连接其他信号
    connect(ui->comboBoxGroupFilter, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &DeviceManager::onGroupFilterChanged);
    connect(ui->tabWidget, &QTabWidget::currentChanged, this, &DeviceManager::onTabChanged);
}

void DeviceManager::setupDeviceModel()
{
    if (!deviceModel) return;

    deviceModel->setTable("devices");
    deviceModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

    if (deviceModel->select()) {
        editDeviceHeaderData(deviceModel);
        ui->tableViewDevices->setModel(deviceModel);
        ui->tableViewDevices->resizeColumnsToContents();
        ui->statusbar->showMessage(QString("设备数据加载成功：共%1条记录").arg(deviceModel->rowCount()));

        // 记录系统日志
        LogManager::logSystem("设备管理模块",
                            QString("设备列表模型加载成功，共 %1 条记录").arg(deviceModel->rowCount()));
    } else {
        QString error = deviceModel->lastError().text();
        QMessageBox::critical(this, "错误", "设备数据查询失败: " + error);

        // 记录错误日志
        LogManager::logError("设备数据查询失败: " + error, currentUserId);
    }
}

void DeviceManager::setupDeviceManagementModel()
{
    if (!deviceManagementModel) return;

    deviceManagementModel->setTable("devices");
    deviceManagementModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

    if (deviceManagementModel->select()) {
        editDeviceHeaderData(deviceManagementModel);
        ui->tableViewDevices_2->setModel(deviceManagementModel);
        ui->tableViewDevices_2->resizeColumnsToContents();
        ui->statusbar->showMessage(QString("设备管理数据加载成功：共%1条记录").arg(deviceManagementModel->rowCount()));

        // 记录系统日志
        LogManager::logSystem("设备管理模块",
                            QString("设备管理模型加载成功，共 %1 条记录").arg(deviceManagementModel->rowCount()));
    } else {
        QString error = deviceManagementModel->lastError().text();
        QMessageBox::critical(this, "错误", "设备管理数据查询失败: " + error);

        // 记录错误日志
        LogManager::logError("设备管理数据查询失败: " + error, currentUserId);
    }
}

void DeviceManager::setupGroupModel()
{
    // 清空并重新初始化下拉框
    ui->comboBoxGroupFilter->clear();
    ui->comboBoxGroupFilter->addItem("所有设备", "");

    // 从数据库查询所有唯一的设备类型
    QSqlQuery query;
    if (query.exec("SELECT DISTINCT type FROM devices WHERE type IS NOT NULL AND type != '' ORDER BY type")) {
        int typeCount = 0;

        while (query.next()) {
            QString deviceType = query.value(0).toString();
            ui->comboBoxGroupFilter->addItem(deviceType, deviceType);
            typeCount++;
        }

        // 记录系统日志
        LogManager::logSystem("设备管理模块",
                            QString("设备类型分组加载成功，共 %1 种设备类型").arg(typeCount));

        // 如果没有找到任何设备类型，提示用户
        if (typeCount == 0) {
            ui->statusbar->showMessage("数据库中暂无设备类型数据");
            LogManager::logSystem("设备管理模块", "数据库中未找到任何设备类型");
        }
    } else {
        QString error = query.lastError().text();
        LogManager::logError("加载设备类型失败: " + error, currentUserId);
        QMessageBox::warning(this, "警告", "加载设备类型失败: " + error);
    }
}

void DeviceManager::editDeviceHeaderData(QSqlTableModel *model)
{
    if (!model) return;

    // 根据图片中的数据库结构设置表头
    model->setHeaderData(model->fieldIndex("device_id"), Qt::Horizontal, "设备ID");
    model->setHeaderData(model->fieldIndex("name"), Qt::Horizontal, "设备名称");
    model->setHeaderData(model->fieldIndex("type"), Qt::Horizontal, "设备类型");
    model->setHeaderData(model->fieldIndex("location"), Qt::Horizontal, "位置");
    model->setHeaderData(model->fieldIndex("manufacturer"), Qt::Horizontal, "制造商");
    model->setHeaderData(model->fieldIndex("model"), Qt::Horizontal, "型号");
    model->setHeaderData(model->fieldIndex("installation_date"), Qt::Horizontal, "安装日期");
    model->setHeaderData(model->fieldIndex("status"), Qt::Horizontal, "状态");
    model->setHeaderData(model->fieldIndex("created_at"), Qt::Horizontal, "创建时间");
    model->setHeaderData(model->fieldIndex("updated_at"), Qt::Horizontal, "更新时间");
}

void DeviceManager::applyUserPermissions()
{
    if (currentUserRole == "user") {
                // 禁用所有工具栏动作
                ui->actionOpenDB->setEnabled(true);  // 允许打开数据库
                ui->actionAddDevice->setEnabled(false);
                ui->actionDeleteDevice->setEnabled(false);
                ui->actionSave->setEnabled(false);
                ui->actionAddGroup->setEnabled(false);
                ui->actionDeleteGroup->setEnabled(false);

                // 设置表格为只读
                ui->tableViewDevices->setEditTriggers(QAbstractItemView::NoEditTriggers);
                ui->tableViewDevices_2->setEditTriggers(QAbstractItemView::NoEditTriggers);

                // 允许搜索和分组查询
                ui->btnSearch->setEnabled(true);
                ui->lineEditSearch->setEnabled(true);
                ui->comboBoxGroupFilter->setEnabled(true);
            }
}

void DeviceManager::onOpenDatabase()
{
    QString fileName = QFileDialog::getOpenFileName(this, "打开数据库", "", "数据库文件 (*.db)");
    if (fileName.isEmpty()) {
        // 记录操作日志（用户取消操作）
        LogManager::logOperation(currentUserId, "打开数据库", "用户取消选择数据库文件", "", "");
        return;
    }

    // 记录操作日志
    LogManager::logOperation(currentUserId, "打开数据库",
                           QString("选择数据库文件: %1").arg(fileName), "", "");

    QSqlDatabase dataBase = QSqlDatabase::addDatabase("QSQLITE");
    dataBase.setDatabaseName(fileName);

    if (dataBase.open()) {
        qDebug() << "数据库连接成功";

        // 记录系统日志
        LogManager::logSystem("设备管理模块",
                            QString("数据库连接成功: %1").arg(fileName));

        // 创建设备模型（设备列表标签页）
        if (deviceModel) {
            delete deviceModel;
            deviceModel = nullptr;
        }
        deviceModel = new QSqlTableModel(this, dataBase);
        setupDeviceModel();

        // 创建设备管理模型（设备管理标签页）
        if (deviceManagementModel) {
            delete deviceManagementModel;
            deviceManagementModel = nullptr;
        }
        deviceManagementModel = new QSqlTableModel(this, dataBase);
        setupDeviceManagementModel();

        // 设置分组过滤器（使用设备类型）
        setupGroupModel();

    } else {
        QString error = dataBase.lastError().text();
        QMessageBox::critical(this, "错误", "数据库连接失败: " + error);

        // 记录错误日志
        LogManager::logError("数据库连接失败: " + error, currentUserId);
    }
}

void DeviceManager::onAddDevice()
{
    QString tabName = (ui->tabWidget->currentIndex() == 0) ? "设备列表" : "设备管理";

    // 记录操作日志
    LogManager::logOperation(currentUserId, "添加设备",
                           QString("在 %1 标签页添加新设备").arg(tabName), "", "");

    QSqlTableModel *currentModel =
        (ui->tabWidget->currentIndex() == 0) ? deviceModel : deviceManagementModel;

    if (!currentModel) {
        QMessageBox::warning(this, "警告", "请先打开数据库");

        // 记录错误日志
        LogManager::logError("添加设备失败: 数据库未打开", currentUserId);
        return;
    }

    int row = currentModel->rowCount();
    if (!currentModel->insertRow(row)) {
        QMessageBox::critical(this, "错误", "添加新设备失败");

        // 记录错误日志
        LogManager::logError("添加新设备行失败", currentUserId);
        return;
    }

    // 设置默认值
    currentModel->setData(currentModel->index(row, currentModel->fieldIndex("status")), "offline");
    currentModel->setData(currentModel->index(row, currentModel->fieldIndex("created_at")),
                         QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    currentModel->setData(currentModel->index(row, currentModel->fieldIndex("updated_at")),
                         QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));

    ui->statusbar->showMessage("已添加新设备行，请填写设备信息后保存");

    // 记录系统日志
    LogManager::logSystem("设备管理模块",
                        QString("已添加新设备行，等待用户填写信息"));
}

void DeviceManager::onDeleteDevice()
{
    QString tabName = (ui->tabWidget->currentIndex() == 0) ? "设备列表" : "设备管理";

    QSqlTableModel *currentModel =
        (ui->tabWidget->currentIndex() == 0) ? deviceModel : deviceManagementModel;
    QTableView *currentTableView =
        (ui->tabWidget->currentIndex() == 0) ? ui->tableViewDevices : ui->tableViewDevices_2;

    if (!currentModel) {
        QMessageBox::warning(this, "警告", "请先打开数据库");

        // 记录错误日志
        LogManager::logError("删除设备失败: 数据库未打开", currentUserId);
        return;
    }

    QModelIndex index = currentTableView->currentIndex();
    if (!index.isValid()) {
        QMessageBox::warning(this, "警告", "请选择要删除的设备");

        // 记录操作日志（无效操作）
        LogManager::logOperation(currentUserId, "删除设备",
                               "未选择要删除的设备", "", "");
        return;
    }

    QString deviceName = currentModel->data(currentModel->index(index.row(),
                                    currentModel->fieldIndex("name"))).toString();
    QString deviceId = currentModel->data(currentModel->index(index.row(),
                                    currentModel->fieldIndex("device_id"))).toString();

    // 记录操作日志（尝试删除）
    LogManager::logOperation(currentUserId, "删除设备",
                           QString("尝试删除设备: %1 (ID: %2)").arg(deviceName).arg(deviceId),
                           "", "");

    if (QMessageBox::question(this, "确认删除",
                              QString("确定要删除设备 '%1' 吗？").arg(deviceName),
                              QMessageBox::Yes | QMessageBox::No)
        == QMessageBox::Yes) {
        currentModel->removeRow(index.row());
        ui->statusbar->showMessage("已删除设备，请保存更改");

        // 记录操作日志（确认删除）
        LogManager::logOperation(currentUserId, "删除设备",
                               QString("确认删除设备: %1 (ID: %2)").arg(deviceName).arg(deviceId),
                               "", "");
    } else {
        // 记录操作日志（取消删除）
        LogManager::logOperation(currentUserId, "删除设备",
                               QString("取消删除设备: %1 (ID: %2)").arg(deviceName).arg(deviceId),
                               "", "");
    }
}

void DeviceManager::onSaveChanges()
{
    // 记录操作日志
    LogManager::logOperation(currentUserId, "保存设备更改", "开始保存所有设备更改", "", "");

    bool success = true;
    QStringList errorMessages;
    int savedCount = 0;

    // 分别保存每个模型
    if (deviceModel && deviceModel->isDirty()) {
        if (deviceModel->submitAll()) {
            deviceModel->select(); // 刷新数据
            savedCount++;
            LogManager::logSystem("设备管理模块", "设备列表数据保存成功");
        } else {
            success = false;
            QString error = deviceModel->lastError().text();
            errorMessages << "设备数据保存失败: " + error;
            deviceModel->revertAll();

            // 记录错误日志
            LogManager::logError("设备数据保存失败: " + error, currentUserId);
        }
    }

    if (deviceManagementModel && deviceManagementModel->isDirty()) {
        if (deviceManagementModel->submitAll()) {
            deviceManagementModel->select(); // 刷新数据
            savedCount++;
            LogManager::logSystem("设备管理模块", "设备管理数据保存成功");
        } else {
            success = false;
            QString error = deviceManagementModel->lastError().text();
            errorMessages << "设备管理数据保存失败: " + error;
            deviceManagementModel->revertAll();

            // 记录错误日志
            LogManager::logError("设备管理数据保存失败: " + error, currentUserId);
        }
    }

    if (success) {
        if (savedCount > 0) {
            QMessageBox::information(this, "成功", "所有更改已保存");
            ui->statusbar->showMessage("保存成功");

            // 记录操作日志（成功保存）
            LogManager::logOperation(currentUserId, "保存设备更改",
                                   QString("成功保存 %1 个模型的更改").arg(savedCount), "", "");
        } else {
            ui->statusbar->showMessage("没有需要保存的更改");

            // 记录系统日志
            LogManager::logSystem("设备管理模块", "没有检测到需要保存的更改");
        }
    } else {
        QMessageBox::critical(this, "错误", errorMessages.join("\n"));

        // 记录错误日志
        LogManager::logError("保存设备更改失败: " + errorMessages.join("; "), currentUserId);
    }
}

void DeviceManager::onSearchDevice()
{
    QString searchText = ui->lineEditSearch->text().trimmed();

    // 记录操作日志
    LogManager::logOperation(currentUserId, "搜索设备",
                           QString("搜索关键词: %1").arg(searchText), "", "");

    if (!deviceManagementModel) {
        QMessageBox::warning(this, "警告", "请先打开数据库");

        // 记录错误日志
        LogManager::logError("搜索设备失败: 数据库未打开", currentUserId);
        return;
    }

    if (searchText.isEmpty()) {
        deviceManagementModel->setFilter("");
    } else {
        // 支持多字段搜索
        QString filter = QString("name LIKE '%%1%' OR type LIKE '%%1%' OR location LIKE '%%1%' OR manufacturer LIKE '%%1%'")
                        .arg(searchText);
        deviceManagementModel->setFilter(filter);
    }

    if (deviceManagementModel->select()) {
        int recordCount = deviceManagementModel->rowCount();
        ui->statusbar->showMessage(QString("查询成功：找到%1条设备记录").arg(recordCount));

        // 记录系统日志
        LogManager::logSystem("设备管理模块",
                            QString("设备搜索成功，关键词: %1，找到 %2 条记录").arg(searchText).arg(recordCount));
    } else {
        QString error = deviceManagementModel->lastError().text();
        ui->statusbar->showMessage("查询失败");

        // 记录错误日志
        LogManager::logError("设备搜索失败: " + error, currentUserId);
    }
}

void DeviceManager::onAddGroup()
{
    // 记录操作日志
    LogManager::logOperation(currentUserId, "添加设备类型", "用户尝试添加新的设备类型", "", "");

    bool ok;
    QString groupName = QInputDialog::getText(this, "添加设备类型",
                                            "请输入新的设备类型:",
                                            QLineEdit::Normal,
                                            "", &ok);

    if (ok && !groupName.isEmpty()) {
        ui->comboBoxGroupFilter->addItem(groupName, groupName);
        ui->statusbar->showMessage(QString("已添加设备类型：%1").arg(groupName));

        // 记录操作日志
        LogManager::logOperation(currentUserId, "添加设备类型",
                               QString("成功添加设备类型: %1").arg(groupName), "", "");
    } else if (ok) {
        // 记录操作日志（用户输入为空）
        LogManager::logOperation(currentUserId, "添加设备类型", "用户输入为空，取消添加", "", "");
    }
}

void DeviceManager::onDeleteGroup()
{
    // 获取当前选中的分组
    int currentIndex = ui->comboBoxGroupFilter->currentIndex();

    // 不能删除"所有设备"选项（索引0）
    if (currentIndex <= 0) {
        QMessageBox::warning(this, "警告", "无法删除'所有设备'选项");
        LogManager::logOperation(currentUserId, "删除设备类型", "尝试删除'所有设备'选项，操作被阻止", "", "");
        return;
    }

    QString groupName = ui->comboBoxGroupFilter->currentText();

    // 记录操作日志
    LogManager::logOperation(currentUserId, "删除设备类型",
                           QString("尝试删除设备类型: %1").arg(groupName), "", "");

    // 确认删除
    if (QMessageBox::question(this, "确认删除",
                              QString("确定要删除设备类型 '%1' 吗？\n注意：这只会从下拉列表中移除，不会影响数据库中的设备数据。").arg(groupName),
                              QMessageBox::Yes | QMessageBox::No)
        == QMessageBox::Yes) {

        // 从下拉框中移除该项
        ui->comboBoxGroupFilter->removeItem(currentIndex);
        ui->statusbar->showMessage(QString("已删除设备类型：%1").arg(groupName));

        // 记录操作日志
        LogManager::logOperation(currentUserId, "删除设备类型",
                               QString("成功删除设备类型: %1").arg(groupName), "", "");

        // 自动切换到"所有设备"
        ui->comboBoxGroupFilter->setCurrentIndex(0);
    } else {
        // 记录操作日志（取消删除）
        LogManager::logOperation(currentUserId, "删除设备类型",
                               QString("取消删除设备类型: %1").arg(groupName), "", "");
    }
}
void DeviceManager::onGroupFilterChanged(int index)
{
    if (!deviceManagementModel) return;

    QString deviceType = ui->comboBoxGroupFilter->itemData(index).toString();

    // 记录操作日志
    LogManager::logOperation(currentUserId, "设备类型过滤",
                           QString("选择设备类型: %1").arg(deviceType.isEmpty() ? "所有设备" : deviceType),
                           "", "");

    if (deviceType.isEmpty()) {
        deviceManagementModel->setFilter("");
    } else {
        deviceManagementModel->setFilter(QString("type = '%1'").arg(deviceType));
    }

    if (deviceManagementModel->select()) {
        int recordCount = deviceManagementModel->rowCount();
        ui->statusbar->showMessage(QString("分组过滤成功：显示%1条设备记录").arg(recordCount));

        // 记录系统日志
        LogManager::logSystem("设备管理模块",
                            QString("设备类型过滤成功，类型: %1，显示 %2 条记录").arg(deviceType).arg(recordCount));
    } else {
        QString error = deviceManagementModel->lastError().text();
        LogManager::logError("设备类型过滤失败: " + error, currentUserId);
    }
}

void DeviceManager::onTabChanged(int index)
{
    QString tabName = (index == 0) ? "设备列表" : "设备管理";
    ui->statusbar->showMessage(QString("当前标签：%1").arg(tabName));

    // 记录操作日志
    LogManager::logOperation(currentUserId, "切换标签页",
                           QString("切换到 %1 标签页").arg(tabName), "", "");
}

void DeviceManager::closeEvent(QCloseEvent *event)
{
    bool hasUnsavedChanges = false;
    if (deviceModel && deviceModel->isDirty()) hasUnsavedChanges = true;
    if (deviceManagementModel && deviceManagementModel->isDirty()) hasUnsavedChanges = true;

    if (hasUnsavedChanges) {
        // 记录操作日志（有未保存更改）
        LogManager::logOperation(currentUserId, "关闭设备管理", "检测到未保存的更改，询问用户", "", "");

        int result = QMessageBox::question(this, "确认退出",
                                          "有未保存的更改，确定要退出吗？",
                                          QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);

        if (result == QMessageBox::Save) {
            onSaveChanges();
            event->accept();

            // 记录操作日志（用户选择保存后退出）
            LogManager::logOperation(currentUserId, "关闭设备管理", "用户选择保存更改后退出", "", "");
        } else if (result == QMessageBox::Discard) {
            event->accept();

            // 记录操作日志（用户选择放弃更改退出）
            LogManager::logOperation(currentUserId, "关闭设备管理", "用户选择放弃未保存的更改并退出", "", "");
        } else {
            event->ignore();

            // 记录操作日志（用户取消退出）
            LogManager::logOperation(currentUserId, "关闭设备管理", "用户取消退出操作", "", "");
        }
    } else {
        event->accept();

        // 记录操作日志（正常退出）
        LogManager::logOperation(currentUserId, "关闭设备管理", "没有未保存的更改，正常退出", "", "");
    }

    // 记录系统日志
    LogManager::logSystem("设备管理模块", "设备管理窗口关闭");
}
